package club.zbiao.modules.system.service.impl;

import club.zbiao.exception.EntityExistException;
import club.zbiao.modules.system.domain.Menu;
import club.zbiao.modules.system.domain.Role;
import club.zbiao.modules.system.repo.RoleRepository;
import club.zbiao.modules.system.service.RoleService;
import club.zbiao.modules.system.service.dto.RoleDTO;
import club.zbiao.modules.system.service.mapper.RoleMapper;
import club.zbiao.utils.ValidationUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.Set;

/**
 * @author jie
 * @date 2018-12-03
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl extends BaseServiceImpl<RoleDTO, Role, RoleMapper, RoleRepository> implements RoleService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public RoleDTO create(Role resources) {
        if (repo.findByName(resources.getName()) != null) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        return mapper.toDto(repo.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role resources) {

        Optional<Role> optionalRole = repo.findById(resources.getId());
        ValidationUtil.isNull(optionalRole, "Role", "id", resources.getId());

        Role role = optionalRole.get();

        Role role1 = repo.findByName(resources.getName());

        if (role1 != null && !role1.getId().equals(role.getId())) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }

        role.setName(resources.getName());
        role.setRemark(resources.getRemark());
        role.setDataScope(resources.getDataScope());
        role.setDepts(resources.getDepts());
        role.setLevel(resources.getLevel());
        repo.save(role);
    }

    @Override
    public void updatePermission(Role resources, RoleDTO roleDTO) {
        Role role = mapper.toEntity(roleDTO);
        role.setPermissions(resources.getPermissions());
        repo.save(role);
    }

    @Override
    public void updateMenu(Role resources, RoleDTO roleDTO) {
        Role role = mapper.toEntity(roleDTO);
        role.setMenus(resources.getMenus());
        repo.save(role);
    }

    @Override
    public void untiedMenu(Menu menu) {
        Set<Role> roles = repo.findByMenus_Id(menu.getId());
        for (Role role : roles) {
            menu.getRoles().remove(role);
            role.getMenus().remove(menu);
            repo.save(role);
        }
    }

}
